#include <GL/glut.h>
#include <stdlib.h>

GLfloat ctrlpoints[100][3];
GLint numPtos;
GLint densidad;
GLfloat xMax, yMax;
int c;
int p;

void init(void)
{
   glClearColor(1.0, 1.0, 1.0, 1.0);
   glShadeModel(GL_FLAT);
   numPtos = 0;
   densidad = 1000;
   c = 1;
   p = 1;
}

void display(void)
{
   int i;

   glClear(GL_COLOR_BUFFER_BIT);
   glColor3f(0.0, 0.0, 1.0);
   
   if (numPtos >= 2 && c) {
     glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, numPtos, &ctrlpoints[0][0]);
     glEnable(GL_MAP1_VERTEX_3);
     glMapGrid1f(densidad, 0.0, 1.0);
     glEvalMesh1(GL_LINE, 0, densidad);
     //glBegin(GL_LINE_STRIP);
     //  for (i = 0; i <= densidad; i++) 
     //      glEvalCoord1f((GLfloat) i/(GLfloat) densidad);
     //glEnd();
   }
     
   /* El siguiente código dibuja los puntos de control */
   if (p) {
	glPointSize(5.0);
	glColor3f(1.0, 0.0, 0.0);
	glBegin(GL_POINTS);
		for (i = 0; i < numPtos; i++) 
			glVertex3fv(&ctrlpoints[i][0]);
	glEnd();
   }  
   glFlush();
}

void reshape(int w, int h)
{
   glViewport(0, 0, (GLsizei) w, (GLsizei) h);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   if (w <= h) {
      glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w, 
               5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
               xMax = 5.0;
               yMax = 5.0*(GLfloat)h/(GLfloat)w;
   } else {
      glOrtho(-5.0*(GLfloat)w/(GLfloat)h, 
               5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
               xMax = 5.0*(GLfloat)w/(GLfloat)h;
               yMax = 5.0;
   }
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
}

void keyboard(unsigned char key, int x, int y)
{
   switch (key) {
      case 27:
         exit(0);
         break;
      case 8:
         if (numPtos > 0)--numPtos;
         break;
      
      case 'C':   
      case 'c':
		c = !c;
		break;
	
	  case 'P':   
      case 'p':
		p = !p;
		break;
   }
   
   glutPostRedisplay();
}

void mouse (int button, int state, int cx, int cy) {
	
	float x, y;
	
	/* Calculamos las coordenadas de mundo (relativas) apartir de 
	 * las de ventana (absolutas) */
	x = ((GLfloat)cx * 2.0 * xMax) / glutGet(GLUT_WINDOW_WIDTH) - xMax;
	y = yMax - ((GLfloat)cy * 2.0 * yMax) / glutGet(GLUT_WINDOW_HEIGHT);
	
	
	if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
		ctrlpoints[numPtos][0] = x;
		ctrlpoints[numPtos][1] = y;
		ctrlpoints[numPtos][2] = 0.0;
		++numPtos;
	}
	
	glutPostRedisplay();
}

int main(int argc, char** argv)
{
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
   glutInitWindowSize (500, 500);
   glutInitWindowPosition (100, 100);
   glutCreateWindow (argv[0]);
   init();
   
   glutDisplayFunc(display);
   glutReshapeFunc(reshape);
   glutKeyboardFunc(keyboard);
   glutMouseFunc(mouse);
   glutMainLoop();
   
   return 0;
}
